package com.sdk.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.sdk.dao.InfluxdbDemoDao;
import com.sdk.utils.InfluxDBConnUtils;
import com.sdk.bean.CodeInfo;

import org.influxdb.dto.BatchPoints;
import org.influxdb.dto.Point;
import org.influxdb.dto.QueryResult;
import org.influxdb.dto.QueryResult.Result;
import org.influxdb.dto.QueryResult.Series;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class InfluxdbDemoDaoImpl implements InfluxdbDemoDao {

    public static String measurementName = "test";

    @Autowired
    private BatchPoints batchPoints;

    @Autowired
    private InfluxDBConnUtils influxDBConnUtils;

    public void saveMessage(List<CodeInfo> list) throws Exception{

        for(CodeInfo info:list) {
            Point point = Point
                    .measurement(measurementName)
                    .time(System.currentTimeMillis(), TimeUnit.MILLISECONDS)
//                .tag("LINE", "13")   //13号线
//                .tag("STATION", "1")  //车站ID
//                .tag("TYPE", "SCADA")  //系统类型
//                .tag("CODE", "1")    //系统类型编码
//                    .tag("TYPE", "131SCADA")   //13号线    VALUE = 线路+车站+系统类型   基于散列值组合区分类型   便于查询
                    .tag("TAG_CODE", info.getCode())
                    .tag("TAG_NAME", info.getName())

                    .addField("ID", info.getId())
                    .addField("NAME", info.getName())
                    .addField("CODE", info.getCode())
                    .addField("DESCR", info.getDescr())
                    .addField("DESCR_E", info.getDescrE())
                    .addField("CREATED_BY", info.getCreatedBy())
                    .addField("CREATED_AT", info.getCreatedAt())
                    .build();
            batchPoints.point(point);
        }
        influxDBConnUtils.write(batchPoints);
    }

    public List<CodeInfo>  selectMessage() throws Exception{
        String command = "select * from test";
        QueryResult results = influxDBConnUtils.query(command);
        if(results.getResults() == null){
            return null;
        }
        List<CodeInfo> lists = new ArrayList<CodeInfo>();
        for (Result result : results.getResults()) {

            List<Series> series= result.getSeries();

            for (Series serie : series) {
              //  Map<String, String> tags = serie.getTags();   //tag 标签 表名加tag一起作为数据库的索引，主要是key-value形式
                List<List<Object>>  values = serie.getValues();
                List<String> columns = serie.getColumns();
                lists.addAll(getQueryData(columns, values));
            }
        }
        return lists;
    }


    /***整理列名、行数据***/
    private List<CodeInfo> getQueryData(List<String> columns, List<List<Object>>  values) throws Exception{
        List<CodeInfo> lists = new ArrayList<CodeInfo>();

        for (List<Object> list : values) {
            CodeInfo info = new CodeInfo();
            BeanWrapperImpl bean = new BeanWrapperImpl(info);
            for(int i=0; i< list.size(); i++){

                String propertyName = setColumns(columns.get(i));//字段名
                Object value = list.get(i);//相应字段值
                bean.setPropertyValue(propertyName, value);
            }

            lists.add(info);
        }

        return lists;
    }

    /***转义字段***/
    private String setColumns(String column) throws Exception{
        String[] cols = column.split("_");
        StringBuffer sb = new StringBuffer();
        for(int i=0; i< cols.length; i++){
            String col = cols[i].toLowerCase();
            if(i != 0){
                String start = col.substring(0, 1).toUpperCase();
                String end = col.substring(1).toLowerCase();
                col = start + end;
            }
            sb.append(col);
        }
        return sb.toString();
    }
}
